<template>
  <div class="login-account">
    <el-form
      ref="fromRef"
      label-width="60"
      :rules="accountConfig.rules"
      :model="account"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input show-password v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ElForm } from 'element-plus';
import { ref, reactive, defineExpose } from 'vue';

import { useStore } from 'vuex';
import accountConfig from '../config/account-config';
import cache from '@/utils/cache';

const store = useStore();
const fromRef = ref<InstanceType<typeof ElForm>>();

const account = reactive({
  name: cache.getCache('name'),
  password: cache.getCache('password')
});

const accountLoginAction = (isKeepPassword: boolean): void => {
  fromRef.value?.validate((valid) => {
    if (valid) {
      // console.log('登录成功');
      // 1.判断是否需要记住密码
      if (isKeepPassword) {
        // 本地缓存
        cache.setCache('name', account.name);
        cache.setCache('password', account.password);
      } else {
        cache.removeCache('name');
        cache.removeCache('password');
      }
      // 2.开始进行登录逻辑
      store.dispatch('login/accountLoginAction', account);
    }
  });
  // console.log('登录登录');
};

defineExpose({
  accountLoginAction
});
</script>

<style lang="less" scoped>
.login-account {
  width: 100%;
}
</style>
